﻿using EnterpriseWebsiteEntity;
using EnterpriseWebsiteUtil.Extentions;
using EnterpriseWebsiteUtil.Helper;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace EnterpriseWebsiteBLL
{
    public class UserService
    {
        public readonly SqlSugarClient _db;
        public string _jwtSecret;

        public UserService(SqlSugarHelper sqlSugarHelper, IConfiguration config)
        {
            _db = sqlSugarHelper.sugarClient;
            _jwtSecret = config["Jwt:Secret"];
        }

        public async Task<UserEntity> LoginAsync(string username,string password)
        {
            password = password.ToMD5String();
            var entity = await _db.Queryable<UserEntity>()
                .Where(u => u.UserName.Equals(username) && u.PassWord.Equals(password))
                .FirstAsync();
            if (entity != null)
            {
                if (string.IsNullOrEmpty(_jwtSecret))
                {
                    throw new Exception("请配置JWTSecret");
                }
                //更新过期时间
                entity.ExpDate = DateTime.Now.AddMinutes(30);//置30分钟有效
                entity.Token = $"{entity.Id}.{_jwtSecret}.{entity.PassWord}.{DateTime.Now.ToString("yyyyMMddHHmmss")}".ToMD5String();
                _db.Updateable(entity)
                    .ExecuteCommand();
            }
            return entity;
        }

        public UserEntity GetUserById(int id)
        {
            var entity = _db.Queryable<UserEntity>()
                .Where(u => u.Id == id )
                .First();
            return entity;
        }

        public async Task<UserEntity> GetUserByIdAsync(int id)
        {
            var entity = await _db.Queryable<UserEntity>()
                .Where(u => u.Id == id)
                .FirstAsync();
            return entity;
        }

        public UserEntity GetUserByIdAndToken(int id,string token)
        {
            var entity = _db.Queryable<UserEntity>()
                .Where(u => u.Id == id && u.Token.Equals(token))
                .First();
            return entity;
        }

        public async Task<int> LogoutAsync(int id)
        {
            var entity = GetUserById(id);
            if(entity == null)
            {
                throw new Exception($"用户id {id} 不存在");
            }
            entity.Token = string.Empty;
            entity.ExpDate = null;
            return await _db.Updateable(entity)
                .ExecuteCommandAsync();
        }

        public async Task<int> ChangeUserName(int id,string username)
        {
            var entity = await GetUserByIdAsync(id);

            if (entity == null)
                throw new Exception($"用户ID {id} 不存在");
            var exist = await _db.Queryable<UserEntity>()
                .Where(u => u.UserName.Equals(username))
                .AnyAsync();
            if (exist)
            {
                throw new Exception("用户名已存在");
            }
            return await _db.Updateable<UserEntity>(u => new UserEntity() { UserName = username })
             .Where(u => u.Id == id)
             .ExecuteCommandAsync();
        }

        public async Task<int> ChangePasswordAsync(int id, string oldPassword, string newPassword, string confirmPassword)
        {
            var entity = await GetUserByIdAsync(id);

            if (entity == null)
                throw new Exception($"用户ID {id} 不存在");

            if (!entity.PassWord.Equals(oldPassword.ToMD5String()))
                throw new Exception($"修改密码失败，请输入正确的旧密码");

            if(!newPassword.Equals(confirmPassword))
                throw new Exception($"修改密码失败，输入的两次密码不一致");

           newPassword = newPassword.ToMD5String();
           return await  _db.Updateable<UserEntity>(u=> new UserEntity() { PassWord = newPassword })
                .Where(u => u.Id == id)
                .ExecuteCommandAsync();
        }
    }
}
